<template>
  <div class="body" v-loading="loading">
    <div class="detail_header">
      <div class="space_between">
        <template v-if="!header.status || header.status === 'save'">
          <div class="part">
            <el-button type="danger" size="small" icon="el-icon-delete" @click="deleteDetail">删除选择行</el-button>
            <el-button type="danger" size="small" icon="el-icon-delete" @click="deleteDetail0">删除重量0的分录行</el-button>
            <el-button type="primary" size="small" icon="el-icon-plus" @click="addDetail">添加分录行</el-button></div>
          <div class="part">
            <el-button type="primary" size="small" icon="el-icon-check" @click="doSave" :disabled="header.status === 'audit'">&nbsp;保&nbsp;存&nbsp;</el-button>
          </div>
        </template>
      </div>
    </div>
    <el-table :data="boxList" class="detail" height="calc(100vh - 110px)" @selection-change="selectChange">
      <el-table-column label="#" width="50" align="center" type="selection" v-if="!header.status || header.status === 'save'"></el-table-column>
      <el-table-column label="No." width="50" align="right" type="index"></el-table-column>
      <el-table-column label="单号" width="180" prop="billNo"></el-table-column>
      <el-table-column label="箱号" width="160" prop="boxNo"></el-table-column>
      <el-table-column label="物料" width="300" prop="materialNo">
        <template #default="scope">
          <el-select style="width: 100%" filterable remote :remote-method="e => getMaterialList(e)"  @change="setMaterialValue" v-model="scope.row.materialNo" :disabled="header.status === 'audit'" size="small" clearable class="material" placeholder="请输入物料编码或者名称">
            <el-option v-for="item in this.materialList" :key="item.fNumber" :label="item.fNumber + '：' + item.fName + ' ' + item.fSpecification" :value="item.fNumber" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="任务单号" width="300" prop="taskBillNo">
        <template #default="scope">
          <el-select filterable style="width: 100%" remote v-model="scope.row.taskBillNo" :remote-method="e => setBillNo(e)" :disabled="header.status === 'audit'" size="small" clearable class="material" placeholder="请输入生产任务单据号">
            <el-option v-for="item in this.billNoList" :key="item.key" :label="item.key" :value="item.key" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="批号" width="180" prop="batchNo">
        <template #default="scope">
          <el-input size="small" v-model="scope.row.batchNo" clearable :disabled="header.status === 'audit'"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="重量" width="170" align="center">
        <template #default="scope">
          <el-input-number :id="`w_row_${ scope.$index }`" ref="w_row" size="small" v-model="scope.row.count" :precision="2" style="width: 150px;" :min="0" @keyup.enter="addDetailOnRow($event, scope)" @change="changeDetailCount" :disabled="header.status === 'audit'" />
        </template>
      </el-table-column>
      <el-table-column label="备注" width="250" align="remark">
        <template #default="scope">
          <el-input type="text" size="small" v-model="scope.row.comment" :disabled="header.status === 'audit'"/>
        </template>
      </el-table-column>
      <el-table-column label="是否入库" width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.inStock? 'success': 'warning'">{{ scope.row.inStock? '已入库': '未入库' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="rfid" prop="rfid" width="100" align="center">
        <template #default="scope">
          <el-popover v-if="scope.row.rfid" placement="bottom" title="rfid" :width="280" trigger="click" :content="scope.row.rfid">
            <template #reference>
              <el-tag type="success" style="cursor: pointer">已关联</el-tag>
            </template>
          </el-popover>
          <el-tag v-else type="warning">未关联</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="入库时间" prop="prdInTime" width="140" align="center">
        <template #default="scope">{{ formatDate(scope.row.prdInTime) }}</template>
      </el-table-column>
      <el-table-column label="入库单号" align="left" prop="prdInBillNo"></el-table-column>
      <el-table-column label="操作" width="90" fixed="right" v-if="!header.status || header.status === 'save'">
        <template #default="scope">
          <el-button type="text" style="color: var(--el-color-danger)" icon="el-icon-delete" @click="deleteRow(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import {getBillNo, getBoxNo} from '../../utils'

export default {
  data() {
    return {
      loading: false,
      materialLoading: false,
      materialList: [],
      supplierLoading: false,
      supplierList: [],
      header: {},
      boxList: [],
      selection: [],
      billNoList: []
    }
  },
  async mounted() {
    let billNo = this.$route.query.billNo
    if (billNo) {
      return this.getBill(billNo)
    } else {
      this.header.batchNo = dayjs().format('YYYYMMDDHHmmss')
    }
  },
  methods: {
    formatDate(date) {
      if (!date) return ''
      return dayjs(date).format('YYYY-MM-DD HH:mm')
    },
    gotoList() {
      return this.$router.push('/produce/simpleColList')
    },
    async getBill(billNo, reset) {
      if (reset) {
        try {
          await this.$confirm('恢复后未保存数据将被清除，确定恢复吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
        } catch(e) {
          return
        }
      }
      this.loading = true
      try {
        let res = await this.callApi('get_prdcol_bill_detail', { billNo })
        if (res.res) {
          this.materialList = [{ fNumber: res.header.materialNo, fName: res.header.materialName, fSpecification: res.header.materialSpec }]
          this.supplierList = [{ fNumber: res.header.supplierNo, fName: res.header.supplierName }]
          this.header = res.header || {}
          this.boxList = res.boxList || []
          this.changeDetailCount()
        }
      } finally {
        this.loading = false
      }
    },
    async doSave() {
      if (this.boxList.length === 0) {
        this.$message.error('没有分录!')
        return
      }
      for(let i = 0; i < this.boxList.length; i++) {
        if (!this.boxList[i].count) {
          this.$message.error('分录行没有重量!')
          return
        }
        if (!this.boxList[i].materialNo) {
          this.$message.error('分录行没有物料!')
          return
        }
      }
      this.loading = true
      let boxList = []
      for(let i = 0; i < this.boxList.length; i++) {
        boxList.push({
          boxNo: this.boxList[i].boxNo,
          taskBillNo: this.boxList[i].taskBillNo,
          count: this.boxList[i].count,
          comment: this.boxList[i].comment,
          billNo: this.boxList[i].billNo,
          materialNo: this.boxList[i].materialNo,
          batchNo: this.boxList[i].batchNo
        })
      }
      let param = {
        boxList
      }
      try {
        let res = await this.callApi('save_simpleCol_bill', param)
        if (!res.res) {
          return
        }
        this.boxList = []
        this.$message.success('保存完成!')
      } finally {
        this.loading = false
      }
    },
    async setBillNo(key) {
      const res = await this.callApi('get_prd_task_billNo', { key: key })
      if (!res.res) return
      this.billNoList = res.data
    },
    async getMaterialList(val) {
      if (val.length >= 5){
        if (!val) {
          this.materialList = []
          return
        }
        this.materialLoading = true
        try {
          const res = await this.callApi('get_material_by_key', { key: val, pageSize: 20 })
          if (!res.res) return
          this.materialList = res.data
        } finally {
          this.materialLoading = false
        }
      }
    },
    setMaterialValue() {
      if (this.materialList && this.header.materialNo) {
        for(let i = 0; i < this.materialList.length; i++) {
          if (this.materialList[i].fNumber === this.header.materialNo) {
            this.header.materialName = this.materialList[i].fName
            this.header.materialSpec = this.materialList[i].fSpecification
            break
          }
        }
      } else {
        this.header.materialName = ''
        this.header.materialSpec = ''
      }
    },
    selectChange(data) {
      this.selection = data
    },
    async deleteDetail() {
      try {
        await this.$confirm('确定删除吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch(e) {
        return
      }
      this.selection.forEach(sel => {
        for(let i = 0; i < this.boxList.length; i++) {
          if (this.boxList[i].boxNo === sel.boxNo) {
            this.boxList.splice(i, 1)
            break
          }
        }
      })
      this.changeDetailCount()
    },
    async deleteDetail0() {
      try {
        await this.$confirm('确定删除吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch(e) {
        return
      }
      for(let i = this.boxList.length - 1; i >= 0; i--) {
        if (this.boxList[i].count === 0) {
          this.boxList.splice(i, 1)
        }
      }
      this.changeDetailCount()
    },
    addDetail() {
      let arr = {}
      if (this.boxList.length > 0) {
        arr = this.boxList[this.boxList.length - 1]
      }
      let addMap = {
        count: 0,
        boxNo: getBoxNo('CZSH'),
        billNo: getBillNo('CJSH'),
        materialNo: '',
        batchNo: '',
        inStock: false,
        perInBillNo: ''
      }
      if (arr.batchNo !== '') {
        addMap.batchNo = arr.batchNo
      }
      this.boxList.push(addMap)

    },
    addDetailOnRow(e, scope) {
      if (scope.$index === this.boxList.length - 1) {
        if (e.keyCode === 13) {
          this.addDetail()
          this.$nextTick(() => {
            document.querySelector('#w_row_' + ( scope.$index + 1 ) + ' input').focus()
            document.querySelector('#w_row_' + ( scope.$index + 1 ) + ' input').select()
          })
        }
      }
    },
    async deleteRow(idx) {
      try {
        await this.$confirm('确定删除吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch(e) {
        return
      }
      this.boxList.splice(idx, 1)
      this.changeDetailCount()
    },
    changeDetailCount() {
      let total = 0
      for(let i = 0; i < this.boxList.length; i++) {
        total += this.boxList[i].count
      }
      this.header.count = total
    }
  }
}
</script>

<style lang="scss" scoped>
.body {
  padding: 20px 0;
  .header {
    margin-top: 20px;
    position: relative;
    .header_row {
      display: flex;
      >div {
        flex-shrink: 0;
      }
      :deep(.produceDate) {
        .el-input {
          width: 100%!important;
        }
      }
    }
    .audit_icon {
      position: absolute;
      top: -10px;
      left: 60px;
      font-size: 48px;
      color: red;
    }
    .material {
      width: 100%;
    }
    .p3 {
      :deep(.el-form-item__content) {
        display: flex;
        .comment {
          margin-left: 10px;
          word-break: keep-all;
        }
      }
    }
  }
  .detail_header {
    display: flex;
    justify-content: space-between;
    margin-top: 10px;
    .stat {
      display: flex;
      font-size: 15px;
      >div {
        display: flex;
        align-items: baseline;
        line-height: 32px;
        .label {
          text-align: right;
          margin-right: 5px;
          color: #aaa;
        }
        .value {
          min-width: 50px;
          margin-right: 10px;
          color: #666;
        }
      }
    }
  }
}

.space_between{
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
